/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.console.config;

import com.alibaba.nacos.sys.env.EnvUtil;
import com.zaxxer.hikari.util.DriverDataSource;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * self check jdbc is ok, when app run with cluster mode.
 *
 * @author huangchangjin
 * @date 2022-06-15 15:12:00
 */
@Component
public class SelfCheckJdbc {

    @PostConstruct
    private static void verifyJdbcIsOk() {
        String datasourcePlatform = EnvUtil.getProperty("spring.datasource.platform", "");
        if ("".equals(datasourcePlatform)) {
            return;
        }
        String dbUrl = EnvUtil.getProperty("db.url.0", "");
        String dbUser = EnvUtil.getProperty("db.user.0", "nacos");
        String dbPwd = EnvUtil.getProperty("db.password.0", "nacos");
        DataSource dataSource = new DriverDataSource(dbUrl, "com.mysql.cj.jdbc.Driver", new Properties(), dbUser, dbPwd);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            // 测试数据库能否链接上
            jdbcTemplate.execute("select 1");
        } catch (Exception e) {
            System.out.println("e = " + e.getMessage());
            // 出现数据库连接异常，主动退出主线程，便于后续 monit拉起服务
            if (e instanceof CannotGetJdbcConnectionException) {
                Runtime.getRuntime().exit(1);
            }
        }
    }
}